package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.FreedomAdapter;
import com.xn.app.muying.bean.VIPBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2016/12/20.
 */
public class VIPActivity extends BaseActivity implements HttpUtil.OnGetDataListener, View.OnClickListener {

    private ListView lv;
    //数据库
    private DBManager db = null;
    //判断是否为会员
    private boolean isVIP;
    //会员截止日期
    private String vipEndTime;
    //是否有资格试用
    private boolean isCanTrialVIP;
    //标题
    private TextView title;
    //VIP时间
    private TextView viptime;
    //续费
    private TextView renew;
    //付费
    private TextView payfor;
    //试用
    private TextView probation;
    //付费布局
    private LinearLayout vip_linear;
    //获取用户姓名
    private String userName = null;
    private ArrayList<VIPBean> lists = null;
    //加载框
    AlertDialog dialog;
    //类对象
    public static VIPActivity viPActivity = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip);
        db = new DBManager(this);
        initview();

    }

    private void initview() {
        viPActivity = this;
        lv = (ListView) findViewById(R.id.activity_vip_listview);
        title = (TextView) findViewById(R.id.activity_vip_title);
        viptime = (TextView) findViewById(R.id.activity_vip_viptime);
        renew = (TextView) findViewById(R.id.activity_vip_renew);
        payfor = (TextView) findViewById(R.id.activity_vip_payfor);
        probation = (TextView) findViewById(R.id.activity_vip_probation);
        vip_linear = (LinearLayout) findViewById(R.id.vip_linear);
        ImageView back = (ImageView) findViewById(R.id.guan_bi);
        payfor.setOnClickListener(this);
        probation.setOnClickListener(this);
        renew.setOnClickListener(this);
        back.setOnClickListener(this);
        ArrayList<String> list = new ArrayList();
        for (int i = 0; i < 4; i++) {
            list.add(i + "");
        }
        lv.setEnabled(false);
        FreedomAdapter adapter = new FreedomAdapter(VIPActivity.this, list);
        lv.setAdapter(adapter);
    }


    /**
     * 获取用户会员相关信息
     */
    private void getMineInfo(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.UserInfo).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    onJsonMine(bodys, i);
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    private void onJsonMine(String bodys, int i) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            isVIP = jsonObject.optBoolean("isVIP");
            vipEndTime = jsonObject.optString("vipEndTime");
            isCanTrialVIP = jsonObject.optBoolean("isCanTrialVIP");
            if (isVIP) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        title.setText("尊敬的蓓儿母婴会员您好");
                        viptime.setVisibility(View.VISIBLE);
                        String[] strs = vipEndTime.split("T");
                        String[] strs2 = strs[1].split(":");
                        viptime.setText("会员日期：" + strs[0] + " " + strs2[0] + ":" + strs2[1]);
                        renew.setVisibility(View.VISIBLE);
                        payfor.setVisibility(View.GONE);
                        probation.setVisibility(View.GONE);
                        vip_linear.setVisibility(LinearLayout.VISIBLE);
                    }
                });

            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        title.setText("开通蓓儿母婴会员");
                        viptime.setVisibility(View.GONE);
                        renew.setVisibility(View.GONE);
                        if (isCanTrialVIP) {
                            payfor.setVisibility(View.VISIBLE);
                            probation.setVisibility(View.VISIBLE);
                        } else {
                            payfor.setVisibility(View.VISIBLE);
                            probation.setVisibility(View.GONE);
                        }
                        vip_linear.setVisibility(LinearLayout.VISIBLE);
                    }
                });
            }
            if (i == 1) {
                int isVIPint = 0;
                if (isVIP) {
                    isVIPint = 1;
                }
                int isCanTrialVIPint = 0;
                if (isCanTrialVIP) {
                    isCanTrialVIPint = 1;
                }
                //将数据与用户信息绑定
                db.updateUserVIP(isVIPint, isCanTrialVIPint, vipEndTime, userName);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onJsonData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray items = jsonObject.getJSONArray("items");
            lists = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String name = object.optString("name");
                String serviceTypeName = object.optString("serviceTypeName");
                String price = object.optString("price");
                String id = object.optString("id");
                String serviceCount = object.optString("serviceCount");
                VIPBean vipBean = new VIPBean();
                vipBean.setName(name);
                vipBean.setServiceTypeName(serviceTypeName);
                vipBean.setPrice(price);
                vipBean.setId(id);
                vipBean.setServiceCount(serviceCount);
                lists.add(vipBean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.activity_vip_payfor:
                intent.putExtra("name_02", lists.get(0).getName());
                intent.putExtra("type_02", lists.get(0).getServiceTypeName());
                intent.putExtra("price_02", lists.get(0).getPrice());
                intent.putExtra("id_02", lists.get(0).getId());
                intent.putExtra("count_02", lists.get(0).getServiceCount());
                intent.putExtra("sign", "VIPActivity");
                intent.setClass(VIPActivity.this, ReadyPayActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_vip_renew:
                intent.putExtra("name_02", lists.get(0).getName());
                intent.putExtra("type_02", lists.get(0).getServiceTypeName());
                intent.putExtra("price_02", lists.get(0).getPrice());
                intent.putExtra("id_02", lists.get(0).getId());
                intent.putExtra("count_02", lists.get(0).getServiceCount());
                intent.putExtra("sign", "VIPActivity");
                intent.setClass(VIPActivity.this, ReadyPayActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_vip_probation:
                if (NetworkUtil.isNetworkAvailable(VIPActivity.this)) {
                    dialog = new MyAlertDialog().ShowDialog(VIPActivity.this, R.layout.dialog_loading);
                    dialog.setCancelable(true);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                HashMap<String, Object> param = new HashMap<>();
                                param.put("serviceProductId", lists.get(1).getId());
                                param.put("productCount", 1);
                                param.put("payMethod", "WechatAppPay");
                                String p = new Gson().toJson(param);
                                RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                                Request request = new Request.Builder().url(APIMethod.WXPay).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).post(formBody).build();
                                okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                                int code = response.code();
                                String str = response.toString();
                                if (code == 204 || code == 200) {
                                    handler.sendEmptyMessage(0);
                                } else {
                                    handler.sendEmptyMessage(1);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();

                            }
                        }
                    }).start();
                } else {
                    ToastUtil.showToast(VIPActivity.this, R.string.no_network_hint);
                }
                break;
            case R.id.guan_bi:
                finish();
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    getMineInfo(1);
                    sendBroadcast(new Intent("bei_er").putExtra("bei_er", 0));
                    if (ZhangHuActivity.zhangHuActivity != null) {
                        ZhangHuActivity.zhangHuActivity.finish();
                    }
                    finish();
                    break;
                case 1:
                    ToastUtil.showToast(VIPActivity.this, "开通失败");
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (NetworkUtil.isNetworkAvailable(VIPActivity.this)) {
            userName = db.select("tel");
            if (userName != null && !userName.equals("") && !userName.equals("null") && db.select("identityId") != null) {
                getMineInfo(0);
            }
            HttpUtil.getData(APIMethod.Buy_Time(2), handler, this);
        }
    }

}
